---
import { getW3FormattedDate, getFormattedDate } from '@/utils/date.utils';
import { posts } from '@/content/posts';
import Base from '@/layouts/Base.astro';
import Text from '@/components/Text/Text.astro';
import Stack from '@/components/Stack/Stack.astro';
import { Icon } from 'astro-icon/components';

const title = 'Blog';

const sortedPosts = posts.sort(
  (a, b) => new Date(b.date).valueOf() - new Date(a.date).valueOf(),
);

const formattedPosts = sortedPosts.map((post) => {
  const formattedPost = {
    title: post.title,
    author: post.author,
    w3FormattedDate: getW3FormattedDate(post.date),
    formattedDate: getFormattedDate(post.date),
    url: post.url?.startsWith('http') ? post.url : `/posts/${post.url}/`,
  };
  return formattedPost;
});
---

<Base title={title}>
  <Stack as="ul" gap={12} axis="y" class="blog-list u-list-style:none">
    {
      formattedPosts.map((post) => (
        <li>
          <Stack as="article" gap={2} class="article">
            <a href={post.url} target="_blank">
              {post.title}
              <Icon
                name="external"
                aria-label="External link"
                role="graphics-symbol img"
              />
            </a>
            <Text as="p" variant="sm">
              <time datetime={post.w3FormattedDate}>{post.formattedDate}</time>
            </Text>
          </Stack>
        </li>
      ))
    }
  </Stack>
</Base>

<style lang="scss">
  .article {
    p {
      margin: 0;
    }
  }

  .blog-list {
    margin: 0;
    padding: 0;
  }
</style>
